﻿#include "GPSDeal.h"
#include "stdaxf.h"
#include "common/mystring.h"
#include "ntripdeal.h"
#include <iostream>

std::string GPSDeal::GenerateGPGGAcode()
{
	return "";
}

void GPSDeal::ProcessNMEAdata(const std::string &dataconnt)
{
	// 跨平台差异
#ifdef _WIN32
	int charlocation = dataconnt.find_last_of('\r\n');
#else
	int charlocation = dataconnt.find_last_of('\n');
#endif // _WIN32

	std::string data = dataconnt.substr(0, charlocation);
	charlocation = data.find_last_of('$');
	if (charlocation == -1 || charlocation + 1 > data.length() - 5) 
	{
		return;
	}

	std::string x = data.substr(charlocation,data.size()- charlocation);
	charlocation = x.find_first_of('*');
	if (charlocation == -1)
	{
		return;
	}
	if (x.length() < charlocation + 3)
	{
		return;
	}
	else if (x.length() > charlocation + 3)
	{
		x = x.substr(1, x.size() - charlocation - 3);
	}
	else
	{

	}
	if (x.length() < 8)
	{
		return;
	}
	std::vector<std::string> aryNMEALine;
	MyString::split(x, "*", &aryNMEALine);
	std::string tmp = aryNMEALine[0];
	MyString::string_replace(tmp, "$", "");
	if (CalculateChecksum(tmp) == aryNMEALine[1])
	{
		std::string left = aryNMEALine[0].substr(0,6);
		if (left == "$GPRMC" || left == "$GNRMC")
		{
			ProcessGPRMC(aryNMEALine[0]);
		}
		if (left == "$GPGGA" || left == "$GNGGA")
		{
			NtripDeal::MostRecentGGA = x;
			ProcessGPGGA(aryNMEALine[0]);
			if (false) 
			{
				// 记录到文件中
			}
		}
		if (left == "$GPGSA" || left == "$GNGSA")
		{
			ProcessGPGSA(aryNMEALine[0]);
		}
	}
}

std::string GPSDeal::CalculateChecksum(const std::string &sentence)
{
	char Character;
	int Checksum = 0;
	for (int i = 0; i < sentence.size(); i++) 
	{
		Character = sentence.at(i);
		switch (Character)
		{
		case '$':
		case '*':
			continue;
			break;
		default:
		{
			if (Checksum == 0)
			{
				Checksum = Character;
			}
			else
			{
				Checksum = Checksum ^ Character;
			}
			break;
		}
		
		}
	}
	unsigned char hex[2];
	MyString::DectoHex(Checksum, hex, 2,false);
	return MyString::convert_hex(hex, 1);
}

void GPSDeal::ProcessGPGGA(const std::string &code)
{

}
void GPSDeal::ProcessGPGSA(const std::string &code)
{

}
void GPSDeal::ProcessGPRMC(const std::string &code)
{

}
